import React from 'react'
import ReactECharts from 'echarts-for-react'
import type { EChartsOption } from 'echarts'

export interface BarChartData {
  name: string
  value: number
  color?: string
}

export interface BarChartProps {
  data: BarChartData[]
  height?: number | string
  title?: string
  yAxisName?: string
  horizontal?: boolean
}

/**
 * 柱状图组件
 * 用于分类数据对比
 */
const BarChart: React.FC<BarChartProps> = ({
  data,
  height = 400,
  title,
  yAxisName = '数值',
  horizontal = false
}) => {
  const option: EChartsOption = {
    title: title ? {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    } : undefined,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params: any) => {
        const item = params[0]
        return `<div>
          <div style="font-weight: bold; margin-bottom: 4px;">${item.name}</div>
          <div>${yAxisName}: ${item.value.toLocaleString()}</div>
        </div>`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: horizontal ? {
      type: 'value',
      name: yAxisName,
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + 'w'
          }
          return value.toString()
        }
      }
    } : {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        interval: 0,
        rotate: data.length > 6 ? 45 : 0
      }
    },
    yAxis: horizontal ? {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        interval: 0
      }
    } : {
      type: 'value',
      name: yAxisName,
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + 'w'
          }
          return value.toString()
        }
      }
    },
    series: [{
      type: 'bar',
      data: data.map(item => ({
        value: item.value,
        itemStyle: {
          color: item.color || '#1890ff'
        }
      })),
      barWidth: '60%',
      label: {
        show: true,
        position: horizontal ? 'right' : 'top',
        formatter: (params: any) => {
          const value = params.value
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + 'w'
          }
          return value.toLocaleString()
        }
      }
    }]
  }

  return (
    <ReactECharts
      option={option}
      style={{ height, width: '100%' }}
      opts={{ renderer: 'canvas' }}
    />
  )
}

export default BarChart
